package view;

import com.alibaba.fastjson.JSON;
import com.mchange.v2.lang.StringUtils;
import mode.ViewForGrid;
import org.apache.poi.util.StringUtil;
import pond.common.STRING;
import pond.db.Record;
import pond.db.sql.Criterion;
import pond.db.sql.Sql;
import pond.db.sql.SqlSelect;
import pond.web.Render;
import pond.web.Router;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Created by sky_wang on 2017/2/22.
 */
public class ShowView extends Router {
    {
        get("/all_views", (req, resp) -> {
            List<Record> ret = App.DB.get(t -> t.query("select distinct (view_name) from view_for_grid;"));
            resp.render(Render.json(ret));
        });

        get("/view_item", (req, resp) -> {
            String view_name = req.paramNonBlank("show_view_name", "show_view_name不能为空");
            List<ViewForGrid> ret = App.DB.get(t -> t.query(ViewForGrid.class, "select * from view_for_grid where view_name = '" + view_name + "';"));
            resp.render(Render.json(ret.get(0)));
        });

        get("/data_of_view", (req, resp) -> {
            String view_name = req.paramNonBlank("show_view_name", "show_view_name不能为空");
            String query_data  = req.param("query_data");
            SqlSelect g_sql = Sql.select("*").from(view_name);
            if (STRING.notBlank(query_data))
            {
                List<Map<String,Object>> list = (List<Map<String,Object>>)JSON.parse(query_data);

                for (Map<String,Object> item : list){
                    String item_key =  (String)item.get("key");
                    Map<String, String> subItem = (Map<String, String>)item.get("value");
                    if ("in".equals(subItem.get("key"))){
                        g_sql.where(item_key, Criterion.EQ, subItem.get("value"));
                    }
                    if ("equal".equals(subItem.get("key"))){
                        g_sql.where(item_key, Criterion.EQ, subItem.get("value"));
                    }
                }
            }
            List<Record> lst = App.DB.get(t -> t.query(g_sql));
            resp.render(Render.json(lst));
        });
    }
}
